package com.simple.space.util;

import com.simple.space.common.constant.Constant;
import com.simple.space.config.global.GlobalConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

public class WebUtil {
    private static final Logger logger = LoggerFactory.getLogger(WebUtil.class);

    public static String uploadPath = "";

    static {
        GlobalConfig globalConfig = SpringContextUtil.getBean(GlobalConfig.class);
        uploadPath = globalConfig.getImgUploadPath();
    }

    public static String getUploadPath(String typeName) {
        return uploadPath + typeName;
    }

    public static String getUploadFilePath(String typeName, String fileName) {
        return Constant.FILE_SEPARATOR + Constant.UPLOAD_PREFIX + Constant.FILE_SEPARATOR+ typeName + Constant.FILE_SEPARATOR  + fileName;
    }

    /**
     * 通过文件路径获取文件名称（ 仅保留文件名不保留后缀 ）
     * @param path
     * @return
     */
    public static String getFileName(String path) {
        if (StringUtils.isBlank(path)){
            return null;
        }
        int start = path.lastIndexOf(Constant.FILE_SEPARATOR );
        int end = path.lastIndexOf(Constant.FILE_SUFFIX );
        if (start != -1) {
            return path.substring(start+1,end);
        } else {
            return null;
        }
    }

    /**
     * 通过文件路径获取文件名称（ 仅保留文件名不保留后缀 ）
     * @param path
     * @return
     */
    public static String getFileSuffix(String path) {
        if (StringUtils.isBlank(path)){
            return null;
        }
        int start = path.lastIndexOf(Constant.FILE_SUFFIX );
        if (start != -1) {
            return path.substring(start);
        } else {
            return null;
        }
    }

    /**
     * @param
     * @return String
     * @throws
     * @title uploadFile
     * @description 文件上传
     */
    public static String uploadFile(MultipartFile file, String type,String oldFilePath) {
        // 由于后台管理多处使用到图片下拉选择，故若是更新，则不更换文件名称，免去改了图片，又得到相关模块重新选择图片的问题
        String suffix = getFileSuffix(oldFilePath);
        String fileName = getFileName(oldFilePath);
        if(StringUtils.isBlank(fileName)){
            fileName= UUID.randomUUID().toString().replaceAll("-", "");
            suffix =  file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        }

        String filePath = getUploadPath(type);
        deleteFileByPath(filePath + Constant.FILE_SEPARATOR +fileName + suffix);
        suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        File tempFile = new File(filePath, String.valueOf(fileName+suffix));
        boolean succ = false;
        try {
            if (!tempFile.getParentFile().exists()) {
                succ = tempFile.getParentFile().mkdirs();
            }
            if (!tempFile.exists()) {
                succ = tempFile.createNewFile();
            }
            if (succ) {
                file.transferTo(tempFile);
            }

        }  catch (Exception e) {
            logger.error("上传图片异常",e);
        }
        return getUploadFilePath(type, tempFile.getName());
    }

    public  static boolean  deleteFileByPath(String path){
        if (StringUtils.isNotBlank(path)){
            File oldFile = new File(path);
            if (oldFile.exists()){
                return oldFile.delete();
            }
        }
        return false;
    }

    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + File.separator  + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + File.separator  + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    // 删除文件夹
    // param folderPath 文件夹完整绝对路径
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
